const express = require('express');
const { Op } = require('sequelize');
const router = express.Router();
const { Chapter, Course } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { NotFound, BadRequest } = require('http-errors');

/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{rank: (number|*), video: (string|boolean|MediaTrackConstraints|VideoConfiguration|*), title, courseId: (number|*), content}}
 */
const filterBody = (req) => {
  if (!req.body.courseId) {
    throw new BadRequest('获取章节失败，课程ID不能为空。');
  }
  return {
    courseId: req.body.courseId,
    title: req.body.title,
    content: req.body.content,
    video: req.body.video,
    rank: req.body.rank,
    free: req.body.free,
  };
};

/**
 * 公共方法：关联课程数据
 * @returns {{include: [{as: string, model, attributes: string[]}], attributes: {exclude: string[]}}}
 */
const getCondition = () => {
  return {
    attributes: { exclude: ['CourseId'] },
    include: [
      {
        model: Course,
        as: 'course',
        attributes: ['id', 'name'],
      },
    ],
  };
};

/**
 * 公共方法：查询当前章节
 */
const getChapter = async (req) => {
  // 获取章节 ID
  const { id } = req.params;

  // 查询当前章节
  const chapter = await Chapter.findByPk(id, getCondition());

  // 如果没有找到，就抛出异常
  if (!chapter) {
    throw new NotFound(`ID: ${id}的章节未找到`);
  }

  return chapter;
};

/**
 * 查询章节列表
 * GET /admin/chapters
 */
router.get('/', async (req, res) => {
  try {
    const query = req.query;

    if (!query.courseId) {
      throw new BadRequest('获取章节列表失败，课程ID不能为空。');
    }

    // 当前是第几页，如果不传，那就是第一页
    const currentPage = Math.abs(Number(query.current)) || 1;
    // 每页显示多少条数据，如果不传，那就显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算 offset
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      ...getCondition(),
      order: [
        ['rank', 'ASC'],
        ['id', 'DESC'],
      ],
      limit: pageSize,
      offset,
      where: {
        courseId: query.courseId,
      },
    };
    if (query.title) {
      condition.where.title = {
        [Op.like]: `%${query.title}%`,
      };
    }
    // 查询数据
    const { count, rows } = await Chapter.findAndCountAll(condition);

    success(res, '查询章节列表成功', {
      data: rows,
      total: count,
    });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 查询章节详情
 * GET /admin/chapters/:id
 */
router.get('/:id', async (req, res) => {
  try {
    // 查询数据
    const chapter = await getChapter(req);
    success(res, '查询章节详情成功', { data: chapter });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 创建章节
 * GPOST /admin/chapters/add
 */
router.post('/add', async (req, res) => {
  try {
    // 创建章节
    const chapter = await Chapter.create(filterBody(req));
    await Course.increment('chaptersCount', {
      where: { id: chapter.courseId },
    });
    success(res, '创建章节成功', { data: chapter }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除章节
 * DELETE /admin/chapters/:id
 */
router.delete('/:id', async (req, res) => {
  try {
    const chapter = await getChapter(req);
    // 删除章节
    await chapter.destroy();
    await Course.decrement('chaptersCount', {
      where: { id: chapter.courseId },
    });
    success(res, '删除章节成功');
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 更新章节
 * PUT /admin/chapters/:id
 */
router.put('/:id', async (req, res) => {
  try {
    const chapter = await getChapter(req);
    // 更新章节
    const updateChapter = await chapter.update(filterBody(req));
    success(res, '更新章节成功', { data: updateChapter });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
